package cn.edu.scnu.semart.cart.service.impl;

import cn.edu.scnu.semart.cart.feign.GoodsFeignClient;
import cn.edu.scnu.semart.cart.mapper.CartMapper;
import cn.edu.scnu.semart.cart.service.CartService;
import cn.edu.scnu.semart.model.cart.Cart;
import cn.edu.scnu.semart.model.cart.CartItemDTO;
import cn.edu.scnu.semart.model.goods.Goods;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private GoodsFeignClient goodsFeignClient;

    @Override
    @Transactional
    public void addOrUpdateCart(Cart cart) {
        if (cart == null || cart.getUserId() == null || cart.getProductId() == null) {
            throw new IllegalArgumentException("购物车数据不完整");
        }

        if (cart.getQuantity() == null || cart.getQuantity() <= 0) {
            throw new IllegalArgumentException("商品数量必须大于0");
        }

        // 1. 先查是否已经存在
        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getUserId, cart.getUserId())
                .eq(Cart::getProductId, cart.getProductId());
        Cart existItem = cartMapper.selectOne(queryWrapper);
        if (existItem != null) {
            // 2. 已存在：按 userId+productId 更新数量
            LambdaUpdateWrapper<Cart> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Cart::getUserId, cart.getUserId())
                    .eq(Cart::getProductId, cart.getProductId())
                    .setSql("quantity = quantity + " + cart.getQuantity());
            cartMapper.update(null, updateWrapper);
        } else {
            // 3. 不存在：直接插入
            cartMapper.insert(cart);
        }
    }

    @Override
    public void updateCartItem(Cart cart) {
        if (cart == null || cart.getCartId() == null) {
            throw new IllegalArgumentException("购物车项ID不能为空");
        }
        // 数量合法性检查（传了才校验）
        if (cart.getQuantity() != null && cart.getQuantity() <= 0) {
            throw new IllegalArgumentException("商品数量必须大于0");
        }
        // 只更新非 null 字段
        cartMapper.updateById(cart);
    }

    @Override
    public void deleteCartItem(Integer cartId) {
        if (cartId == null || cartId <= 0) {
            throw new IllegalArgumentException("无效的购物车项ID");
        }
        cartMapper.deleteById(cartId);
    }

    @Override
    public void batchDeleteCartItems(List<Integer> cartIds) {
        if (CollectionUtils.isEmpty(cartIds)) {
            throw new IllegalArgumentException("购物车项ID列表不能为空");
        }

        if (cartIds.size() > 100) {
            throw new IllegalArgumentException("一次最多删除100个购物车项");
        }

        cartMapper.deleteBatchIds(cartIds);
    }

    @Override
    public List<CartItemDTO> getUserCart(Integer userId) {
        if (userId == null || userId <= 0) {
            throw new IllegalArgumentException("无效的用户ID");
        }

        // 1. 查询用户购物车基础数据
        List<Cart> cartList = cartMapper.selectByUserId(userId);
        if (cartList.isEmpty()) return Collections.emptyList();

        // 2. 获取商品ID列表
        List<Integer> productIds = cartList.stream()
                .map(Cart::getProductId)
                .distinct()
                .collect(Collectors.toList());

        // 3. Feign调用批量获取商品详情
        Map<Integer, Goods> productMap = new HashMap<>();

        try {
            // 分批查询，每批最多50个商品ID
            int batchSize = 50;
            for (int i = 0; i < productIds.size(); i += batchSize) {
                int end = Math.min(i + batchSize, productIds.size());
                List<Integer> batchIds = productIds.subList(i, end);

                List<Goods> batchProducts = goodsFeignClient.getBatchByIds(batchIds);
                if (batchProducts != null && !batchProducts.isEmpty()) {
                    for (Goods product : batchProducts) {
                        productMap.put(product.getId(), product);
                    }
                }
            }
        } catch (Exception e) {
            // 如果批量查询失败，记录错误但不中断
            System.err.println("批量查询商品失败: " + e.getMessage());
            // 可以添加日志记录
        }

        // 4. 组装DTO
        return cartList.stream().map(cart -> {
            CartItemDTO dto = new CartItemDTO();
            dto.setCartId(cart.getCartId());
            dto.setUserId(cart.getUserId());
            dto.setProductId(cart.getProductId());
            dto.setQuantity(cart.getQuantity());
            dto.setSelected(cart.getSelected());
            dto.setAddedTime(cart.getAddedTime());

            // 设置商品信息
            Goods product = productMap.get(cart.getProductId());
            if (product != null) {
                dto.setProductName(product.getGoodsName());
                dto.setProductPrice(product.getPrice());
                dto.setProductImage(product.getMainImage());
                dto.setSellerId(product.getUserId());
                dto.setSellerName(product.getUserName());
                dto.setProductDescription(product.getDescription());
                // 设置库存状态
                if (product.getStock() != null) {
                    // 0: 有货, 1: 缺货
                    dto.setStockStatus(product.getStock() > 0 ? 0 : 1);
                } else {
                    dto.setStockStatus(1); // 未知库存视为缺货
                }
            } else {
                // 商品不存在或获取失败
                dto.setProductName("商品信息不可用");
                dto.setProductPrice(null);
                dto.setStockStatus(2); // 2: 商品已下架或不可用
            }

            return dto;
        }).collect(Collectors.toList());
    }
}
